/**
 * @param {number} n
 * @param {number} a
 * @param {number} b
 * @return {number}
 */
var nthMagicalNumber = function (n, a, b) {
  const MOD = 1000000007
  let left = Math.min(a, b)
  let right = n * Math.min(a, b)
  let minNum = lcm(a, b)
  while(left<=right){
    let mid = Math.floor((left+right)/2)
    let count = Math.floor(mid/a)+Math.floor(mid/b)-Math.floor(mid/minNum)
    if(count<=n){
      right=mid-1
    }else{
      left = mid+1
    }
  }
  return right+1%MOD

  function lcm(a, b) {
    return (a * b) / gcb(a, b)
  }

  function gcb(a, b) {
    return b === 0 ? a : gcb(b, a % b)
  }
}
